<template>
  <div>
    <h1>{{ id ? "编辑" : "新建" }}物品</h1>
    <!-- <el-form label-width="120px" @submit.native.prevent="save"> -->
    <!-- <el-form label-width="120px" @submit.native.prevent :rules="rules"> -->
    <el-form label-width="120px" @submit.native.prevent>
      <!-- <el-form-item label="名称" prop="name"> -->
      <el-form-item label="名称">
        <el-input v-model="model.name"></el-input>
      </el-form-item>
      <el-form-item label="图标">
        <el-upload
          class="avatar-uploader"
          :action="mixinUploadURL"
          :headers="mixingetAuthHeaders()"
          :show-file-list="false"
          :on-success="afterUpload"
        >
          <img v-if="model.icon" :src="model.icon" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" navite-type="submit" @click="save"
          >保存</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: {
    id: {}
  },
  data() {
    return {
      model: {}
    };
  },
  methods: {
    // 图片上传成功后执行的方法
    afterUpload(res) {
      console.log(res);
      // vue 响应式绑定数据 未定义属性的对象 后面新增属性是不具备响应式的 要用 $set 来设置
      this.$set(this.model, "icon", res.url);
      // this.model.icon = res.url;
      console.log(this.model);
    },
    // 新建分类的方法
    async save() {
      if (this.id) {
        // 修改物品名
        await this.$http.put(`rest/items/${this.id}`, this.model);
      } else {
        // console.log("save操作");
        // 提交数据
        await this.$http.post("rest/items", this.model);
        // console.log(res);
      }
      this.$router.push("/items/list");
      this.$message({
        type: "success",
        message: "保存成功"
      });
    },
    // 根据传过来的 _id 获取需要修改的物品名
    async fetch() {
      const res = await this.$http.get(`rest/items/${this.id}`);
      this.model = res.data;
    }
  },
  created() {
    this.id && this.fetch();
    console.log(this.model.icon);
  }
};
</script>
